import React, {Component} from 'react'
import {Table, FormControl, Select, Button } from 'tinper-bee'
const Option = Select.Option;
import {
    getcompListData,
    getProjectData,
    getPkOrgList,
    getPrintCode
} from './signInreportconfig'
import './index.less';
import App from "../../layout/App";
import {
    vendorsSuccess,
    vendorsDanger,
    vendorsFmtDate,
    vendorsSetStorage,
    vendorsGetStorage,
    vendorsGetTId
} from 'utils/config.js';
import RangePicker from "../../components/RangePicker/index.jsx";
import ProjectModal from "../../components/ProjectModal/index.jsx";



export default class SignInReport extends Component {
    constructor(props) {
        super(props);
        let _me = this;
        this.compTitle = '企业名称:';
        this.projectTitle = '项目名称:';
        this.compListData = [];
        this.projectListData = [];
        this.compColumns = [
            {
                title: "序号", dataIndex: "num", key: "num", width: '5%',
                render(text, record, index) {
                    return (
                        <span>{index + 1}</span>
                    )
                }
            },
            {title: "姓名", dataIndex: "userName", key: "userName", width: '20%'},
            {title: "出勤天数", dataIndex: "signInDays", key: "signInDays", width: '20%'},
            {title: "合计时长", dataIndex: "totalHours", key: "totalHours", width: '20%'},
            {
                title: "操作", dataIndex: "opr", key: "opr", width: '35%',
                render(text, rec, index) {
                    return (
                        <div onClick={() => {
                            _me.handleDetailAction(rec)
                        }}
                             style={{color: '#1884EE', cursor: 'pointer'}}>
                            个人详情
                        </div>
                    )
                }
            }
        ];
        this.projectColumns = [
            {
                title: "序号", dataIndex: "num", key: "num", width: '5%',
                render(text, record, index) {
                    return (
                        <span>{index + 1}</span>
                    )
                }
            },
            {title: "姓名", dataIndex: "userName", key: "userName", width: '10%'},
            {title: "企业名称", dataIndex: "enterpriseName", key: "enterpriseName", width: '20%'},
            {title: "出勤天数", dataIndex: "signInDays", key: "signInDays", width: '10%'},
            {title: "合计时长", dataIndex: "totalHours", key: "totalHours", width: '20%'},
            {
                title: "操作", dataIndex: "opr", key: "opr", width: '35%',
                render(text, rec, index) {
                    return (
                        <div
                            onClick={() => {
                                _me.handleDetailAction(rec)
                            }}
                            style={{color: '#1884EE', cursor: 'pointer'}}>
                            个人详情
                        </div>
                    )
                }
            }
        ];
        this.state = {
            showModal: false,
            formValue: [],
            selectValue: '',
            orgList: [],
            startTime: '',
            endTime: '',
            curFlag: 'comp',
            contentTitle: this.compTitle,
            columns: this.compColumns,
            tableListData: [],
            checkedPks: [],
            modalListData: [],
            modelState:{},
            scrollTopN:0
        };
    }
    clearPkOrg=()=>{
        this.setState({
            selectValue:''
        })
    };
    componentDidMount() {
        let singInRePageData = vendorsGetStorage('singInRePageData');
        if (singInRePageData) {
            let {detailFlag, stateParams, compListData, projectListData} = vendorsGetStorage('singInRePageData')
            if (detailFlag) {
                this.compListData = compListData;
                this.projectListData = projectListData;
                let {curFlag} = stateParams;
                this.setState({
                    ...stateParams,
                    columns: curFlag == 'comp' ? this.compColumns : this.projectColumns,
                }, () => {
                    document.documentElement.scrollTop = this.state.scrollTopN;
                    vendorsSetStorage('singInRePageData', {...singInRePageData, detailFlag: false});
                })
            } else {
                //获取组织列表
                this.getPkOrgListAction();
                //默认时间
                this.getTime()
            }
        } else {
            //获取组织列表
            this.getPkOrgListAction();
            //默认时间
            this.getTime()
        }
        //select清除
        let target = document.getElementsByClassName('u-select-selection__clear')[0];
        target.addEventListener("click", this.clearPkOrg);
    }

    setChildren = (children, childrenArr) => {
        if (children && children.length) {
            children.forEach((item) => {
                if (item.pkSrc) {
                    childrenArr.push(item);
                    if (item["children"]) {
                        this.setChildren(item["children"], childrenArr)
                    }
                }
            })
        }
    };
    getPkOrgListAction = () => {
        getPkOrgList().then((res) => {
            let data = res.data;
            if (data.resultCode !== 'busi_ex') {
                let {children} = data.result;
                children = children ? children : [];
                let selectValue = '';
                let childrenArr = [];
                this.setChildren(children, childrenArr);
                selectValue = childrenArr[0].pkSrc;
                this.setState({
                    orgList: childrenArr
                })
            } else {
                vendorsDanger({'text': data.exMsg})
            }
        })
    };

    componentWillUnmount() {

    };

    handleDetailAction = (record) => {
        let {startTime, endTime, selectValue, curFlag} = this.state;
        let detAjaxParams = {
            userId: record.pkUser,
            timeStart: Date.parse(startTime) - 8*60*60*1000,
            timeEnd: Date.parse(endTime) + 16*60*60*1000
        };
        if (curFlag === 'comp') {
            detAjaxParams.orgId = selectValue;
            detAjaxParams.enterpriseId = record.pkEnterprise
        }
        if (curFlag === 'project') {
            detAjaxParams.projectId= record.pkProject
        }
        this.setState({
            scrollTopN:document.documentElement.scrollTop || document.body.scrollTop
        },()=>{
            let params = {
                stateParams: this.state,
                compListData: this.compListData,
                projectListData: this.projectListData,
                record,
                detailFlag: true,
                detAjaxParams
            };
            vendorsSetStorage('singInRePageData', params);
            window.location.href = '/signinreportdetail.html'
        })
    };
    changeSearchLimit = (limitStr) => {
        let columns = limitStr === 'comp' ? this.compColumns : this.projectColumns;
        let contentTitle = limitStr === 'comp' ? this.compTitle : this.projectTitle;
        let tableListData = limitStr === 'comp' ? this.compListData : this.projectListData;
        this.setState({
            curFlag: limitStr,
            columns,
            contentTitle,
            tableListData
        })
    };
    onSelectChange = (value) => {
        this.setState({
            selectValue: value,
            checkedPks:[],
            formValue:[]
        })
    };
    onTimeChange = (timeArr) => {
        let startTime = vendorsFmtDate(timeArr[0]);
        let endTime = vendorsFmtDate(timeArr[1]);
        this.setState({
            startTime,
            endTime
        });
    };
    getTime = (startTime, endTime) => {
        if (startTime) {
            startTime = Date.parse(startTime);
            endTime = Date.parse(endTime);
        } else {
            endTime = new Date().getTime();
            startTime = endTime - 30 * 24 * 60 * 60 * 1000;
        }
        this.setState({
            startTime: vendorsFmtDate(startTime),
            endTime: vendorsFmtDate(endTime)
        });
    };
    setParams = (curFlag) => {
        let {selectValue, startTime, endTime, checkedPks} = this.state;
        let params = {
            timeStart: Date.parse(startTime) - 8*60*60*1000,
            timeEnd: Date.parse(endTime) + 16*60*60*1000
        };
        if (selectValue) {
            params.orgId = selectValue
        }
        if (curFlag === 'project'&&checkedPks.length) {
            params.projectIds = this.state.checkedPks
        }
        return params
    };
    onSearchSubmit = () => {
        let {curFlag} = this.state;
        if (curFlag === 'project') {
            getProjectData(this.setParams(curFlag)).then((res) => {
                let data = res.data;
                if (data.resultCode !== 'busi_ex') {
                    vendorsSuccess({'text': '查询成功'});
                    this.projectListData = data.result;
                    // this.compListData = [];
                    this.setState({
                        tableListData: data.result
                    })
                } else {
                    vendorsDanger({'text': data.exMsg})
                }
            })
        } else {
            getcompListData(this.setParams(curFlag)).then((res) => {
                let data = res.data;
                if (data.resultCode !== 'busi_ex') {
                    vendorsSuccess({'text': '查询成功'});
                    this.compListData = data.result;
                    // this.projectListData = [];
                    this.setState({
                        tableListData: data.result
                    })
                } else {
                    vendorsDanger({'text': data.exMsg})
                }
            })
        }

    };
    formConClick = () => {
        this.setState({
            showModal: true,
        })
    };
    closeModel = (modelState) => {
        this.setState({
            showModal: false,
            modelState
        });
    };
    saveModalTabledata = (res) => {
        let stateParams ={
            modalListData: res,
        };
        this.setState(stateParams)
    };
    sureClick = (checkedProjectName,checkedPks) => {
       this.setState({
           checkedPks:checkedPks,
           formValue:checkedProjectName
       })
    };
    printAction=()=>{
        vendorsGetTId().then((tenantId)=>{
            let params = this.setParams(this.state.curFlag);
            let boCode = 'pm_signin_projectlist_report';
            let printUrl = '/signInStatistic/printListByProjects';
            if(this.state.curFlag == 'comp'){
                boCode = 'pm_signin_enterpriselist_report';
                printUrl = '/signInStatistic/printListByEnts'
            }
            getPrintCode({
                'isAjax': 1, ieStamp: new Date().getTime(), boCode, tenantId
            }).then(function (response) {
                if (response.data.resultCode != 'busi_ex') {
                    let data = response.data.result;
                    let url = `./print/preview?serverUrl=${printUrl}&printcode=${data}&tenantId=${tenantId}&sendType=2&params=${JSON.stringify(params)}`;
                    window.open(encodeURI(url));
                } else {
                    vendorsDanger({ 'text': response.data.exMsg });
                }
            });
        });
    };
    render() {
        let {showModal, formValue, selectValue, orgList, startTime, endTime, curFlag, columns, tableListData, contentTitle} = this.state;
        return (
            <App>
                <div className='report-sign-in'>
                    {/*<Affix childrenRef={null} zIndex={2001}>*/}
                        <div className='sign-in-search-area'>
                            <div className='search-area-org clearfix'>
                                <div className='org-search-area'>
                                    <span>项目组织:</span>
                                    <Select
                                        showSearch
                                        optionFilterProp="children"
                                        notFoundContent="没有相关条目"
                                        className="bill-body-form-select inline-block"
                                        allowClear={'allowClear'}
                                        style={{width: 280, marginLeft: 6}}
                                        size="lg"
                                        value={selectValue}
                                        onSelect={this.onSelectChange}
                                        placeholder='请选择'
                                    >
                                        {
                                            orgList.map((item) => {
                                                return <Option value={item.pkSrc} key={item.pkSrc}>{item.sname}</Option>
                                            })
                                        }
                                    </Select>
                                </div>
                                <div className='org-button-area'>
                                    <Button className="search--btn" colors="primary"
                                            onClick={this.printAction}>打印考勤记录</Button>
                                </div>
                            </div>
                            <div className='search-area-other clearfix'>
                                <div className='search-area-opr'>
                                    <span>筛选:</span>
                                    <div className='opr'>
                                        <div className={curFlag === 'comp' ? 'cur-opr cur-opr-show' : 'cur-opr'}
                                             onClick={() => {
                                                 this.changeSearchLimit('comp')
                                             }}>
                                            企业查询
                                        </div>
                                        <div className={curFlag === 'project' ? 'cur-opr cur-opr-show' : 'cur-opr'}
                                             onClick={() => {
                                                 this.changeSearchLimit('project')
                                             }}>
                                            项目查看
                                        </div>
                                    </div>
                                </div>
                                <div className='search-area-opr clearfix'>
                                    <span style={{float: 'left'}}>起止时间:</span>
                                    <div className='opr' style={{float: 'left'}}>
                                        <RangePicker
                                            startTime={startTime}
                                            endTime={endTime}
                                            onChange={this.onTimeChange}
                                        />
                                    </div>
                                </div>
                                {
                                    curFlag === 'project' ? <div className='search-area-opr clearfix'>
                                            <span style={{float: 'left'}}>项目:</span>
                                            <div className='opr' style={{float: 'left'}}>
                                                <FormControl
                                                    type="search"
                                                    showClose
                                                    style={{width: '230px'}}
                                                    value={formValue.join()}
                                                    placeholder="请选择"
                                                />
                                                <div className='opr-l-click' onClick={this.formConClick}></div>
                                            </div>
                                        </div> :
                                        null
                                }
                                <Button className="search--btn" colors="primary" onClick={this.onSearchSubmit}>搜索</Button>
                            </div>
                        </div>
                    {/*</Affix>*/}



                    <div className='sign-in-content-area'>
                        {
                            tableListData.length ?
                                tableListData.map((item, index) => {
                                        return (
                                            <div key={index}>
                                                <div className='content-area-title'>
                                                    <span>{contentTitle}</span>
                                                    <span
                                                        className='content-area-title-name'>{curFlag == 'comp' ? item.enterpriseName : item.projectName}</span>
                                                </div>
                                                <Table
                                                    columns={columns}
                                                    data={item.reportVO}
                                                    emptyText={() => '暂无数据'}
                                                    scroll={{y: 460}}
                                                    bordered
                                                    // rowKey={this.setRowKey}
                                                />
                                            </div>)
                                    }
                                ) :
                                <div className='empty-container'>暂无数据</div>
                        }
                    </div>
                    <ProjectModal
                        modalListData={this.state.modalListData}
                        saveModalTabledata={this.saveModalTabledata}
                        pkOrg={selectValue}
                        showModal={showModal}
                        closeModel={this.closeModel}
                        sureClick={this.sureClick}
                    />
                </div>
            </App>
        )
    }
}
